/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Block;

import DAO.ConnectDatabase;
import DAO.WeekDao;
import Helper.WeekHelper;
import Model.WeekModel;
import common.CalendarFormat;
import common.Constant;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author KIENLT
 */
public class Weeks extends javax.swing.JPanel {

    ArrayList<WeekHelper> arrWeek;
    ArrayList<WeekHelper> arrWeekList;
    
    WeekHelper weekData;
    ResultSet rs = null;
    /**
     * Creates new form Weeks
     */
    public Weeks() {
        initComponents();
        changeLanguage();
        fillAll();
    }

    private void changeLanguage() {
        if(Constant.getLanguage() == 0){
            Constant.initBundle();
            getLanguage();
        }else{
            Constant.initBundle();
            getLanguage();
        }
    }
    
    private void fillAll(){
        try {
            arrWeek = WeekDao.FillAll(ConnectDatabase.ConnectionDatabase());
            arrWeekList = new ArrayList<WeekHelper>();
            
            for(WeekHelper week : arrWeek){
                arrWeekList.add(week);
            }
            tblWeeks.setModel(new WeekModel(arrWeekList));
            
            if(arrWeekList.size() > 0){
                tblWeeks.getSelectionModel().setSelectionInterval(0, 0);
                fillOne();
            }
            
            tblWeeks.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {                    
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    boolean adjust = e.getValueIsAdjusting();
                    if(adjust && tblWeeks.getSelectedRow() >= 0){
                        fillOne();                       
                    }
                }
            });
            
        } catch (SQLException ex) {
            Logger.getLogger(Weeks.class.getName()).log(Level.SEVERE, null, ex);
        }
         tblWeeks.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         tblWeeks.getColumnModel().getColumn(0).setPreferredWidth(50);
         tblWeeks.getColumnModel().getColumn(1).setPreferredWidth(200);
         tblWeeks.getColumnModel().getColumn(2).setPreferredWidth(200);
    }
    
    private void getLanguage() {
        lblWeekId.setText(Constant.getBundle().getString("weekId"));
        lblDateBegin.setText(Constant.getBundle().getString("dateBegin"));
        lblDateEnd.setText(Constant.getBundle().getString("dateEnd"));
        btnUpdate.setText(Constant.getBundle().getString("update"));
        btnDelete.setText(Constant.getBundle().getString("delete"));
        btnAdd.setText(Constant.getBundle().getString("add"));
    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        lblDateBegin = new javax.swing.JLabel();
        lblDateEnd = new javax.swing.JLabel();
        dcDateBegin = new com.toedter.calendar.JDateChooser();
        dcDateEnd = new com.toedter.calendar.JDateChooser();
        txtWeekId = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        lblWeekId = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblWeeks = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder()));

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblDateBegin.setText("Date Begin");

        lblDateEnd.setText("Date End");

        txtWeekId.setEnabled(false);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x16/add2.png"))); // NOI18N
        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x16/update.png"))); // NOI18N
        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/img_x16/delete2.png"))); // NOI18N
        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        lblWeekId.setText("WeekId");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDateEnd)
                    .addComponent(lblDateBegin)
                    .addComponent(dcDateBegin, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dcDateEnd, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtWeekId, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete))
                    .addComponent(lblWeekId))
                .addContainerGap(16, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(lblWeekId)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtWeekId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblDateBegin)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dcDateBegin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(lblDateEnd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dcDateEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnUpdate)
                    .addComponent(btnDelete)
                    .addComponent(btnAdd))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tblWeeks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tblWeeks);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        try {
            WeekHelper week = new WeekHelper();
            Calendar beginDate = dcDateBegin.getCalendar();
            Calendar endDate = dcDateEnd.getCalendar();
            
            int beginDay = beginDate.get(Calendar.DAY_OF_MONTH);
            int beginMonth = beginDate.get(Calendar.MONTH)+1;
            int beginYear = beginDate.get(Calendar.YEAR);
            
            int endDay = endDate.get(Calendar.DAY_OF_MONTH);
            int endMonth = endDate.get(Calendar.MONTH)+1;
            int endYear = endDate.get(Calendar.YEAR);
            
            String dateBegin = beginYear+"-"+beginMonth+"-"+beginDay;
            String dateEnd = endYear+"-"+endMonth+"-"+endDay;
            week.setDateBegin(dateBegin);
            week.setDateEnd(dateEnd);
            int query = WeekDao.Insert(ConnectDatabase.ConnectionDatabase(), week);
            if(query > 0){
                JOptionPane.showMessageDialog(this, "Insert Success.", "Message", JOptionPane.INFORMATION_MESSAGE);
                fillAll();
            }else{
                JOptionPane.showMessageDialog(this, "Insert Fail.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Weeks.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        updateWeek();
    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        removeTableWeek();
    }//GEN-LAST:event_btnDeleteActionPerformed
    
    private void removeTableWeek() {
        // TODO add your handling code here:
        int[] rows = tblWeeks.getSelectedRows();
        for(int i=rows.length-1; i>=0; i--){
            WeekModel accModel = (WeekModel)tblWeeks.getModel();
            if(!String.valueOf(tblWeeks.getValueAt(rows[i], 0)).equals("")){
                int option = JOptionPane.showConfirmDialog(this, "You are sure delete?", "Message", JOptionPane.YES_NO_OPTION);
                if(option == JOptionPane.YES_OPTION){
                    deleteWeek();
                    accModel.deleteRow(rows[i]);
                }
            }
        }
    }        
    
    private void deleteWeek() {
        weekData = new WeekHelper();
            int[] rows = tblWeeks.getSelectedRows();
            for(int i=0; i<rows.length; i++){
            try {
                System.out.println(tblWeeks.getValueAt(rows[i], 0));
                weekData.setWeekId(String.valueOf(tblWeeks.getValueAt(rows[i], 0)));
                WeekDao.Delete(ConnectDatabase.ConnectionDatabase(), weekData);
            } catch (SQLException ex) {
                Logger.getLogger(Weeks.class.getName()).log(Level.SEVERE, null, ex);
            }
            }
    }
    
    private void fillOne(){
        try {
            weekData = new WeekHelper();
            int row = tblWeeks.getSelectedRow();
            weekData.setWeekId(tblWeeks.getValueAt(row, 0).toString());
            rs = WeekDao.FillOne(ConnectDatabase.ConnectionDatabase(), weekData);
            if(rs.next()){  
                //example
                Calendar futureCal = Calendar.getInstance();
                futureCal.set(2012, 11, 19);
                
                Calendar now = Calendar.getInstance();
                now.set(2012, 11, 15);
                //code 
                txtWeekId.setText(rs.getString("WeekId"));
                
                String[] strBegin = rs.getString("DateBegin").split(" ");
                String[] strBeginDate = strBegin[0].split("-");
                int beginDay = Integer.parseInt(strBeginDate[2]);
                int beginMonth = Integer.parseInt(strBeginDate[1])-1;
                int beginYear = Integer.parseInt(strBeginDate[0]);
                String dateBegin = beginYear+"-"+beginMonth+"-"+beginDay;
                dcDateBegin.setCalendar(CalendarFormat.setCalendar(dateBegin));
                
                String[] strEnd = rs.getString("DateEnd").split(" ");
                String[] strEndDate = strEnd[0].split("-");
                int endDay = Integer.parseInt(strEndDate[2]);
                int endMonth = Integer.parseInt(strEndDate[1])-1;
                int endYear = Integer.parseInt(strEndDate[0]);
                String dateEnd = endYear+"-"+endMonth+"-"+endDay;
                dcDateEnd.setCalendar(CalendarFormat.setCalendar(dateEnd));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Weeks.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void updateWeek(){
        try {
            WeekHelper week = new WeekHelper();
            week.setWeekId(txtWeekId.getText());
            
            Calendar beginDate = dcDateBegin.getCalendar();
            Calendar endDate = dcDateEnd.getCalendar();

            int beginDay = beginDate.get(Calendar.DAY_OF_MONTH);
            int beginMonth = beginDate.get(Calendar.MONTH)+1;
            int beginYear = beginDate.get(Calendar.YEAR);

            int endDay = endDate.get(Calendar.DAY_OF_MONTH);
            int endMonth = endDate.get(Calendar.MONTH)+1;
            int endYear = endDate.get(Calendar.YEAR);

            String dateBegin = beginYear+"-"+beginMonth+"-"+beginDay;
            String dateEnd = endYear+"-"+endMonth+"-"+endDay;
            week.setDateBegin(dateBegin);
            week.setDateEnd(dateEnd);
            
            int query = WeekDao.Update(ConnectDatabase.ConnectionDatabase(), week);
            if(query > 0){
                JOptionPane.showMessageDialog(this, "Update Success.", "Message", JOptionPane.INFORMATION_MESSAGE);
                fillAll();
            }else {
                JOptionPane.showMessageDialog(this, "Update Fail.", "Message", JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Weeks.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnUpdate;
    private com.toedter.calendar.JDateChooser dcDateBegin;
    private com.toedter.calendar.JDateChooser dcDateEnd;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblDateBegin;
    private javax.swing.JLabel lblDateEnd;
    private javax.swing.JLabel lblWeekId;
    private javax.swing.JTable tblWeeks;
    private javax.swing.JTextField txtWeekId;
    // End of variables declaration//GEN-END:variables

    
}
